import React, { useState, useEffect, createContext } from 'react'
import { Swiper, List, Loading, PullRefresh } from 'react-vant'
import { webHome, getDynamicData, recommendActive } from '@/api'
import DataContext from '../../Context/index'
import Card from '@/components/Card'
import './index.less'

const Index = () => {
  let [page, setPage] = useState({
    page: 0,
    page_size: 5,
  })

  const [load, setLoad] = useState(false)

  const [data, setData] = useState({})

  const [finished, setFinished] = useState(false)

  const [add, setAdd] = useState([])

  const [recommend, setRecommendActive] = useState([])

  const init = async (type = 'init') => {
    let res = await webHome({
      gids: 2,
      page: page.page,
      page_size: page.page_size,
    })
    getIdRes(res, type)
  }

  const getIdRes = async (res, type) => {
    let getId = res.data.recommended_posts.map(a => {
      return a.post.post_id
    })
    let IDres = await getDynamicData({ gids: 2, post_ids: getId.join(',') })
    res.data.recommended_posts.forEach(item => {
      IDres.data.list.forEach(ele => {
        if (item.post.post_id == ele.post_id) {
          item.stat = ele.stat
        }
      })
    })
    if (type === 'init') {
      add.push(...res.data.recommended_posts)
    } else {
      setAdd(res.data.recommended_posts)
    }
    setData({
      ...res.data,
      recommended_posts: add,
    })
    setLoad(false)
    setFinished(false)
    setTimeout(() => {
      let first = document.querySelectorAll('.rv-swiper__slide')[0]
      first.className = 'we rv-swiper__slide'
    }, 0)
  }

  const getRecommendActive = async () => {
    let res = await recommendActive({
      gids: 2,
      page_size: 10,
    })
    setRecommendActive(res.data.list)
  }

  const onLoad = () => {
    setPage({
      page: (page.page += 1),
      page_size: page.page_size,
    })
    init()
    setFinished(true)
  }

  const swiperChange = i => {
    let s = Array.from(
      document.querySelectorAll('.rv-swiper__track-inner .rv-swiper__slide')
    )
    s[i].className = 'we rv-swiper__slide'
    s.forEach((a, b) => {
      if (b != i) {
        a.classList.remove('we')
      }
    })
  }

  useEffect(() => {
    setLoad(true)
    getRecommendActive()
  }, [])

  return (
    <>
      {load ? (
        <div className="load">
          <Loading size="60" color="#3f45ff" />
        </div>
      ) : (
        <PullRefresh pullingText="松开刷新" loosingText="松开刷新" onRefresh={() => init('refresh')}>
          <>
            {data.carousels ? (
              <Swiper
                autoplay={3500}
                onChange={swiperChange}
                slideSize={94}
                trackOffset={3}
                className="mhy-card banner-card"
              >
                {data.carousels.map((item, i) => (
                  <Swiper.Item key={i}>
                    <img src={item.cover} alt="" />
                  </Swiper.Item>
                ))}
              </Swiper>
            ) : (
              ''
            )}
            <List
              loadingText={'嘎嘎快嗷兄弟们~'}
              className="home-post-container"
              finished={finished}
              onLoad={onLoad}
            >
              <DataContext.Provider
                value={{
                  topic: data.recommended_topics,
                  recommend: recommend,
                }}
              >
                <Card
                  list={
                    data !== '' && data.recommended_posts
                      ? data.recommended_posts.slice(0)
                      : []
                  }
                />
              </DataContext.Provider>
            </List>
          </>
        </PullRefresh>
      )}
    </>
  )
}

export default Index
